package com.shanjiduo.newsline.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.a1502d.volley.VolleyDataRequester;
import com.android.volley.VolleyError;
import com.github.lianghanzhen.LazyFragmentPagerAdapter;
import com.github.lianghanzhen.LazyViewPager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shanjiduo.newsline.R;
import com.shanjiduo.newsline.WebActivity;
import com.shanjiduo.newsline.adapter.NewsAdapter;
import com.shanjiduo.newsline.model.NewsSummary;
import com.shanjiduo.newsline.view.XListView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NewsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewsFragment extends Fragment implements LazyFragmentPagerAdapter.Laziable, XListView.IXListViewListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private List<NewsSummary> mdata = new ArrayList<NewsSummary>();
    private int index = 0;
    private XListView xlv;
    private NewsAdapter na;

    public NewsFragment() {
        // Required empty public constructor
    }

    public static NewsFragment newInstance(String param1, String param2) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        jsonRequestGetHttpsExample(0, true);
        //可能出错
        initView(view);
        return view;
    }

    private void initView(View view) {
        xlv = (XListView) view.findViewById(R.id.list_news);
        xlv.setPullLoadEnable(true);
        xlv.setPullRefreshEnable(true);
        xlv.setXListViewListener(this);

        xlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                NewsSummary summary = mdata.get(i - 1);
                Intent intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra("url", summary.url_3w);
                startActivity(intent);
            }
        });

    }


    @Override
    public void onRefresh() {
        index++;
        jsonRequestGetHttpsExample(index, false);
        xlv.stopRefresh(true);

    }

    @Override
    public void onLoadMore() {
        index++;
        jsonRequestGetHttpsExample(index, true);
        xlv.stopLoadMore();
    }


    //請求網絡數據
    private void jsonRequestGetHttpsExample(int index, final boolean bo) {
        final String url = "http://c.m.163.com/nc/article/headline/" + mParam2 + "/" + index + "-20.html";
        VolleyDataRequester.withDefaultHttps(getActivity())
                .setUrl(url)
                .setJsonResponseListener(new VolleyDataRequester.JsonResponseListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            //TODO 待解析字符串
                            String s = response.toString();
                            Gson gson = new Gson();

                            Map<String, List<NewsSummary>> map = gson.fromJson(s, new TypeToken<Map<String, List<NewsSummary>>>() {
                            }.getType());
                            if (bo) {
                                mdata.addAll(map.get(mParam2));
                            } else {
                                mdata.clear();
                                mdata.addAll(map.get(mParam2));
                            }

                            if (na == null) {
                                na = new NewsAdapter(getActivity());
                                na.setData(mdata);
                                xlv.setAdapter(na);
                            } else {
                                na.setData(mdata);
                                na.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .setResponseErrorListener(new VolleyDataRequester.ResponseErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                })
                .requestJson();
    }


}
